(function (init) {
    if (typeof Vue === 'undefined') {
        window.addEventListener('load', function () {
            if (typeof Vue !== 'undefined') init();
        });
    } else {
        init();
    }
})(function(){
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                value: '',
                PageNumber: 1,
                RowAmount: 20,
            },
            list: [],
            total: 0,
            dialogContractVisible: false,
            currentContractRow: null,
            // 顶部统一报价原信息
            pageAcquisition: null,
            currentAcqId: '',
            // 权限相关：当前企业与来源
            enterpriseId: '',
            fromQuoteDetail: false,
            // 付款弹窗与表单
            dialogPayVisible: false,
            paySaving: false,
            payContext: null, // { order, stage }
            payForm: { amount: '', voucherList: [] },
            // 收款详情弹窗
            dialogReceiptVisible: false,
            receiptContext: null, // { order, stage }
            receiptView: { contractAmount: '', stageDueAmount: '', actualAmount: '', voucherUrl: '' },
            // 物流发货弹窗与表单（通过交易流水号映射到供应单）
            dialogShipVisible: false,
            shipSaving: false,
            shipContext: null, // { order, stage }
            shipForm: { logisticsCode: '', logisticsNumber: '', voucherList: [] },
            logisticsOptions: [],
            dialogReceiveVisible: false,
            receiveView: null,
            // 收货后临时锁定操作：按订单维度
            _orderActionLockedMap: {},
        }
    },
    mounted() {
        this.getList();
    },
        methods: {
        handleBack() {
            // 若从“我的报价”详情进入（带acqId），返回到“我的报价”列表
            const acqId = (function () {
                try { return getQueryObject(window.location.href, 'acqId') || ''; } catch (e) { return ''; }
            })();
            if (acqId) {
                window.location.href = '../acquisition_order/index.html';
            } else {
                window.location.href = './index.html';
            }
        },
        // 打开发货弹窗
        async openShipDialog(orderRow, stageRow) {
            this.shipContext = { order: orderRow, stage: stageRow };
            this.shipForm = { logisticsCode: '', logisticsNumber: '', voucherList: [] };
            await this.loadLogisticsOptions();
            this.dialogShipVisible = true;
        },
        async loadLogisticsOptions() {
            try {
                const res = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: `Row_Status IN ('0','2','3')` });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.logisticsOptions = arr;
            } catch (e) { this.logisticsOptions = []; }
        },
        onShipVoucherChange(file, fileList) {
            const f = file.raw || file;
            if (!f || !String(f.type || '').startsWith('image/')) {
                this.$message.error('仅支持上传图片文件');
                this.shipForm.voucherList = [];
                return;
            }
            const maxSize = 10 * 1024 * 1024;
            if (f.size && f.size > maxSize) {
                this.$message.error('图片大小不得超过10MB');
                this.shipForm.voucherList = [];
                return;
            }
            this.shipForm.voucherList = fileList.slice(0, 1);
        },
        onShipVoucherRemove(file, fileList) {
            this.shipForm.voucherList = fileList;
        },
        // 保存发货信息：写入 acquisition_order_logistics
        async confirmShip() {
            if (!this.shipContext || !this.shipContext.order) {
                this.$message.error('上下文缺失，无法发货');
                return;
            }
            const order = this.shipContext.order;
            if (!this.shipForm.logisticsCode) {
                this.$message.error('请选择物流公司');
                return;
            }
            if (!this.shipForm.logisticsNumber) {
                this.$message.error('请输入物流单号');
                return;
            }
            this.shipSaving = true;
            try {
                let voucherPath = '';
                if (this.shipForm.voucherList && this.shipForm.voucherList.length > 0) {
                    try {
                        const fileObj = this.shipForm.voucherList[0].raw || this.shipForm.voucherList[0];
                        const uploadRes = await generalApi.generalUploadStream(fileObj);
                        voucherPath = (uploadRes && (uploadRes.Path || uploadRes.url || uploadRes.File_Path)) || '';
                    } catch (e) { this.$message.warning('凭证上传失败，已忽略'); }
                }

                const now = getYMDHMSDate();
                const creator = $.cookie('user') || $.cookie('enterprise') || '';
                const rec = {
                    Acquisition_Order_Logistics_SerialNumber: '',
                    Acquisition_Order_SerialNumber: order.Acquisition_Order_SerialNumber,
                    Logistics_Number: this.shipForm.logisticsNumber,
                    Logistics_Code: this.shipForm.logisticsCode,
                    Delivery_Data: now,
                    Enterprise_Info_SerialNumber: order.Enterprise_Info_SerialNumber || '',
                    Creater_SerialNumber: creator,
                    Create_Datetime: now,
                    Row_Status: '0',
                    Operation_ID: creator,
                    Operation_Datetime: now,
                };
                if (voucherPath) rec.Picture_URL = voucherPath;

                const dataset = { Add: { acquisition_order_logistics: [rec], base_operation_log: [] }, Modify: {} };
                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '求购单发货填写物流',
                    Operation_Main: JSON.stringify({
                        Acquisition_Order_SerialNumber: order.Acquisition_Order_SerialNumber,
                        Logistics_Code: rec.Logistics_Code,
                        Logistics_Number: rec.Logistics_Number
                    }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('发货信息已保存');
                    this.dialogShipVisible = false; this.upsertStageStart(order.Acquisition_Order_SerialNumber, '到货');
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('保存发货信息失败，请稍后再试');
            } finally { this.shipSaving = false; }
        },
        // 查看收货（物流）详情：取最近一次物流记录（acquisition_order_logistics）
        async openReceiveDialog(orderRow) {
            try {
                const list = await generalApi.generalQueryByTableName({
                    Data: 'acquisition_order_logistics',
                    Condition: `Acquisition_Order_SerialNumber='${orderRow.Acquisition_Order_SerialNumber}'`
                });
                const arr = Array.isArray(list) ? list : (list.Data || []);
                let rec = arr && arr[0];
                if (arr && arr.length > 1) {
                    rec = arr.slice().sort((a,b)=> new Date(b.Create_Datetime||0) - new Date(a.Create_Datetime||0))[0];
                }
                if (rec && rec.Logistics_Code) {
                    try {
                        const opts = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: `Logistics_Code='${rec.Logistics_Code}'` });
                        const oa = Array.isArray(opts) ? opts : (opts.Data || []);
                        if (oa && oa[0]) rec.Logistics_Name = oa[0].Logistics_Name;
                    } catch (e) {}
                }
                this.receiveView = rec || null;
                this.dialogReceiveVisible = true; this.upsertStageStart(orderRow.Acquisition_Order_SerialNumber, '尾款');
            } catch (e) { this.$message.error('查询物流信息失败'); }
        },
        // 收货确认：点击后暂时锁定该订单所有操作
        onConfirmReceive() {
            try {
                const oid = (this.receiveView && this.receiveView.Acquisition_Order_SerialNumber) || '';
                if (oid) this.$set(this._orderActionLockedMap, oid, true);
                this.$message.success('已确认收货，操作暂时锁定');
            } catch (e) {}
            this.dialogReceiveVisible = false;
        },
        // 阶段状态控制按钮可操作性（采购页仅使用：付款、收货）
        actionEnabled(stageRow, action) {
            const st = String((stageRow && (stageRow.status || stageRow.Row_Status)) || '');
            switch (action) {
                case 'pay': return st === '待付款';
                case 'receive': return st === '已发货';
                default: return false;
            }
        },
        // 4-待付款，5-已付款，6-待发货，7-已发货
        formatPayStageStatus(st) {
            const s = String(st || '').trim();
            if (s === '4' || s === '待付款') return '待付款';
            if (s === '5' || s === '已付款') return '已付款';
            if (s === '6' || s === '待发货') return '待发货';
            if (s === '7' || s === '已发货') return '已发货';
            return '待付款';
        },
        // 订单是否被锁定（收货后暂时不可操作）
        isOrderLocked(row) {
            const oid = (row && row.Acquisition_Order_SerialNumber) || '';
            return !!this._orderActionLockedMap[oid];
        },
        handleSerach() {
            this.form.PageNumber = 1;
            this.getList();
        },
        formatStatus(status) {
            switch (String(status)) {
                case '0': return '待审核';
                case '2': return '通过';
                case '3': return '拒绝';
                default: return '未知';
            }
        },
        statusTagType(status) {
            switch (String(status)) {
                case '0': return 'warning';
                case '2': return 'success';
                case '3': return 'danger';
                default: return 'info';
            }
        },
        handlePageChange(page) {
            this.form.PageNumber = page;
            this.getList();
        },
        getList() {
            const enterpriseId = $.cookie('enterprise') || '';
            const keyword = this.form.value || '';
            const acqId = (function () {
                try { return getQueryObject(window.location.href, 'acqId') || ''; } catch (e) { return ''; }
            })();
            // 记录当前报价编号
            this.currentAcqId = acqId;
            // 记录当前企业与来源标记（从“我的报价”进入时隐藏操作按钮）
            this.enterpriseId = enterpriseId;
            this.fromQuoteDetail = !!acqId;

            let condition = `Row_Status IN ('0','2','3')`;
            // 指定报价编号筛选或按当前登录企业筛选
            if (acqId) {
                condition += ` AND Acquisition_Unit_Price_SerialNumber='${acqId}'`;
            } else if (enterpriseId) {
                condition += ` AND Enterprise_Info_SerialNumber='${enterpriseId}'`;
            }
            if (keyword) {
                const kw = String(keyword).replace(/'/g, "''");
                condition += ` AND (Acquisition_Order_SerialNumber LIKE '%${kw}%' OR Enterprise_Info_SerialNumber LIKE '%${kw}%')`;
            }

            httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: {
                    Data: 'acquisition_order',
                    Condition: condition,
                    PageNumber: this.form.PageNumber,
                    RowAmount: this.form.RowAmount,
                },
                type: 'GET'
            }).then(async res => {
                if (Array.isArray(res)) {
                    this.list = res;
                    this.total = res.length;
                } else {
                    this.list = res.Data || [];
                    this.total = Number(res.Total || 0);
                }

                // 尝试查询拒绝日志，若无该表或查询失败则忽略
                const ids = (this.list || []).map(i => i.Acquisition_Order_SerialNumber).filter(Boolean);
                if (ids.length > 0) {
                    try {
                        const logs = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'acquisition_order_examine_log',
                                Condition: `Acquisition_Order_SerialNumber IN (${ids.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const arr = Array.isArray(logs) ? logs : (logs.Data || []);
                        const map = {};
                        arr.forEach(l => {
                            const k = l.Acquisition_Order_SerialNumber;
                            if (!map[k]) map[k] = [];
                            map[k].push(l);
                        });
                        this.list = this.list.map(row => ({
                            ...row,
                            examineLogs: map[row.Acquisition_Order_SerialNumber] || []
                        }));
                    } catch (e) {
                        // 无日志表或查询失败，忽略
                    }
                }

                // 追加：批量查询报价原信息（acquisition_unitprice），挂载页面顶部并绑定到每条订单
                const unitIds = [...new Set((this.list || []).map(i => i.Acquisition_Unit_Price_SerialNumber).filter(Boolean))];
                if (unitIds.length > 0) {
                    try {
                        const upRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'acquisition_unitprice',
                                Condition: `Acquisition_Unit_Price_SerialNumber IN (${unitIds.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const upArr = Array.isArray(upRes) ? upRes : (upRes.Data || []);
                        const upMap = {};
                        upArr.forEach(s => { upMap[s.Acquisition_Unit_Price_SerialNumber] = s; });
                        // 绑定到每条记录，便于权限判断
                        this.list = (this.list || []).map(row => ({
                            ...row,
                            originAcquisition: upMap[row.Acquisition_Unit_Price_SerialNumber] || null
                        }));
                        const firstId = (this.list[0] && this.list[0].Acquisition_Unit_Price_SerialNumber) || '';
                        this.pageAcquisition = upMap[this.currentAcqId] || upMap[firstId] || null;

                        // 追加：按报价编号批量查询阶段付款计划，并计算当前订单的应付金额
                        try {
                            const stagedRes = await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: {
                                    Data: 'acquisition_unitprice_staged_payment',
                                    Condition: `Acquisition_Unit_Price_SerialNumber IN (${unitIds.map(id => `'${id}'`).join(',')})`
                                },
                                type: 'POST'
                            }).catch(() => []);
                            const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes.Data || []);
                            const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                            const stagedMap = {};
                            (stagedArr || []).forEach(sp => {
                                const k = sp.Acquisition_Unit_Price_SerialNumber;
                                if (!stagedMap[k]) stagedMap[k] = [];
                                stagedMap[k].push(sp);
                            });
                            Object.keys(stagedMap).forEach(k => {
                                stagedMap[k] = stagedMap[k].slice().sort((a,b)=>{
                                    const ia = orderMap[String(a.Stage_Name||'').trim()] || 99;
                                    const ib = orderMap[String(b.Stage_Name||'').trim()] || 99;
                                    if (ia === ib) {
                                        const ta = new Date(a.Create_Datetime || 0).getTime();
                                        const tb = new Date(b.Create_Datetime || 0).getTime();
                                        return ta - tb;
                                    }
                                    return ia - ib;
                                });
                            });

                            // 映射到每条订单：_stagePaymentsDisplay 与固定四阶段 _stagePaymentsFixed
                            this.list = this.list.map(row => {
                                const amount = Number(row.Amount || 0);
                                const stages = (stagedMap[row.Acquisition_Unit_Price_SerialNumber] || []).map(sp => {
                                    // 付款比例仅显示 Percent 字段；缺失则留空
                                    const pctRaw = (sp.Percent !== undefined && sp.Percent !== null && sp.Percent !== '') ? sp.Percent : '';
                                    const pct = (pctRaw !== '' && !Number.isNaN(Number(pctRaw))) ? Number(pctRaw) : '';
                                    // 应付金额优先：Due_Amount > Trading_Amount；都没有时若有百分比则按金额×百分比，否则留空
                                    let dueRaw = '';
                                    if (sp.Due_Amount !== undefined && sp.Due_Amount !== null && sp.Due_Amount !== '') {
                                        dueRaw = Number(sp.Due_Amount);
                                    } else if (sp.Trading_Amount !== undefined && sp.Trading_Amount !== null && sp.Trading_Amount !== '') {
                                        dueRaw = Number(sp.Trading_Amount);
                                    } else if (pct !== '' && Number.isFinite(Number(amount))) {
                                        dueRaw = Number((amount * pct / 100).toFixed(2));
                                    }
                                    const days = Number(sp.Pay_Time || 0);
                                    const start = new Date(row.Create_Datetime || row.Operation_Datetime || Date.now());
                                    const begin = start.toLocaleDateString();
                                    const end = new Date(start.getTime() + days * 24 * 3600 * 1000).toLocaleDateString();
                                    return {
                                        stage: sp.Stage_Name || '',
                                        percent: (pct !== '' ? pct : ''),
                                        dueAmount: (Number.isFinite(dueRaw) ? Number(Number(dueRaw).toFixed(2)) : ''),
                                        payWindow: days ? `${begin} — ${end}` : ''
                                    };
                                });
                                const stageOrder = ['定金','发货','到货','尾款'];
                                const stageDict = {};
                                stages.forEach(s => { stageDict[String(s.stage||'').trim()] = s; });
                                const fixed = stageOrder.map(name => {
                                    const s = stageDict[name] || {};
                                    return {
                                        stage: name,
                                        percent: (s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : '',
                                        dueAmount: (s.dueAmount !== undefined && s.dueAmount !== null && s.dueAmount !== '') ? s.dueAmount : '',
                                        payWindow: (s.payWindow !== undefined && s.payWindow !== null && s.payWindow !== '') ? s.payWindow : ''
                                    };
                                });
                                return { ...row, _stagePaymentsDisplay: stages, _stagePaymentsFixed: fixed };
                            });
                        } catch (e) {
                            // 阶段付款查询失败忽略，不影响主列表
                        }
                    } catch (e) {
                        // 查询失败忽略
                    }
                }
                // 使用 SQL 标识“supply_payment_stages”渲染阶段（固定四行，查出几条就显示几条数据）
                try {
                    const sqlResults = await Promise.all((this.list || []).map(row =>
                        generalApi.generalQueryBySQLSerialNumber({
                            SQLSerialNumber: 'acquisition_payment_stages',
                            Condition: utf8ToBase64(String(row.Acquisition_Order_SerialNumber || '')),
                            ExtensionCondition: ''
                        }).catch(() => [])
                    ));
                    const stageOrder = ['定金','发货','到货','尾款'];
                    this.list = (this.list || []).map((row, idx) => {
                        const arr = sqlResults[idx];
                        const rows = Array.isArray(arr) ? arr : [];
                        if (!rows || rows.length === 0) return row; // 无数据时保留原映射
    
                        const stages = rows.map(rec => {
                            const pct = Number(
                                (rec.Percent !== undefined && rec.Percent !== null && rec.Percent !== '')
                                    ? rec.Percent
                                    : ''
                            );
                            const dueRaw = (rec.Due_Amount !== undefined && rec.Due_Amount !== null && rec.Due_Amount !== '')
                                ? Number(rec.Due_Amount) : (rec.Trading_Amount !== undefined ? Number(rec.Trading_Amount) : '');
                            const begin = rec.Start_Datetime ? getYMDDate(rec.Start_Datetime) : '';
                            const end = rec.End_Datetime ? getYMDDate(rec.End_Datetime) : '';
                            return {
                                stage: rec.Stage_Name || '',
                                percent: Number.isFinite(pct) ? pct : '',
                                dueAmount: Number.isFinite(dueRaw) ? Number(dueRaw.toFixed(2)) : '',
                                payWindow: (begin && end) ? `${begin} — ${end}` : '',
                                status: this.formatPayStageStatus(rec.Row_Status),
                                serial: rec.Supply_Order_Paystages_SerialNumber || rec.Acquisition_Order_Paystages_SerialNumber || '',
                                quoteStageSerial: rec.Supply_Unit_Price_Staged_Payment_SerialNumber || rec.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '',
                                paidAmount: Number(rec.Paid_Amount || 0)
                            };
                        });
                        const stageDict = {};
                        stages.forEach(s => { stageDict[String(s.stage||'').trim()] = s; });
                        const fixed = stageOrder.map(name => {
                            const s = stageDict[name] || {};
                            return {
                                stage: name,
                                percent: (s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : '',
                                dueAmount: (s.dueAmount !== undefined && s.dueAmount !== null && s.dueAmount !== '') ? s.dueAmount : '',
                                payWindow: (s.payWindow !== undefined && s.payWindow !== null && s.payWindow !== '') ? s.payWindow : '',
                                status: s.status || '待付款',
                                serial: s.serial || '',
                                quoteStageSerial: s.quoteStageSerial || '',
                                paidAmount: (s.paidAmount !== undefined) ? s.paidAmount : 0
                            };
                        });
                        return { ...row, _stagePaymentsDisplay: stages, _stagePaymentsFixed: fixed };
                    });
                } catch (e) {
                // 查询失败忽略
            }

            }).catch(() => {
                this.$message.error('查询失败，请稍后再试');
            });
        },
        // 操作按钮可见性：仅发布采购的企业可见；从“我的报价”详情进入（acqId）则不可见
        canOperate(row) {
            if (this.fromQuoteDetail) return false;
            const pubEnt = (row && row.originAcquisition && row.originAcquisition.Enterprise_Info_SerialNumber) || '';
            return pubEnt && this.enterpriseId && String(pubEnt) === String(this.enterpriseId);
        },
        // 合同确认状态格式化与判定
        formatContractStatus(st) {
            const s = String(st || '');
            if (s === '00') return '未确认';
            if (s === '01') return '乙方已确认';
            if (s === '10') return '甲方已确认';
            if (s === '11') return '甲乙双方确认';
            return '未确认';
        },
        contractStatusTagType(st) {
            const s = String(st || '');
            if (s === '11') return 'success';
            if (s === '01' || s === '10') return 'warning';
            return 'info';
        },
        isContractConfirmed(row) {
            return String((row && row.Contract_Status) || '') === '11';
        },
        // 乙方确认合同：依据当前状态计算下一个状态并保存到 acquisition_order
        async confirmByB(row) {
            try {
                const curr = String((row && row.Contract_Status) || '00');
                if (curr === '01' || curr === '11') {
                    this.$message.info('乙方已确认，无需重复操作');
                    return;
                }
                const next = (curr === '10') ? '11' : '01';

                // 查询订单原记录，修改 Contract_Status
                const arr = await generalApi.generalQueryByTableName({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                if (!Array.isArray(arr) || arr.length !== 1) {
                    this.$message.error('未找到订单数据或存在重复记录');
                    return;
                }
                const od = { ...arr[0], Contract_Status: next };

                const dataset = { Modify: { acquisition_order: [od] }, Add: { base_operation_log: [] } };
                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '求购合同乙方确认',
                    Operation_Main: JSON.stringify({ Acquisition_Order_SerialNumber: row.Acquisition_Order_SerialNumber, From_Status: curr, To_Status: next }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success(next === '11' ? '双方已确认合同' : '乙方已确认合同');
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('乙方确认失败，请稍后再试');
            }
        },
        // 甲方确认合同：依据当前状态计算下一个状态并保存到 acquisition_order
        async confirmByA(row) {
            try {
                const curr = String((row && row.Contract_Status) || '00');
                if (curr === '10' || curr === '11') {
                    this.$message.info('甲方已确认，无需重复操作');
                    return;
                }
                const next = (curr === '01') ? '11' : '10';

                // 查询订单原记录，修改 Contract_Status
                const arr = await generalApi.generalQueryByTableName({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                if (!Array.isArray(arr) || arr.length !== 1) {
                    this.$message.error('未找到订单数据或存在重复记录');
                    return;
                }
                const od = { ...arr[0], Contract_Status: next };

                const dataset = { Modify: { acquisition_order: [od] }, Add: { base_operation_log: [] } };
                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '求购合同甲方确认',
                    Operation_Main: JSON.stringify({ Acquisition_Order_SerialNumber: row.Acquisition_Order_SerialNumber, From_Status: curr, To_Status: next }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success(next === '11' ? '双方已确认合同' : '甲方已确认合同');
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('甲方确认失败，请稍后再试');
            }
        },
        formatRejectLog(log, idx) {
            const reason = (log && log.Reason) ? log.Reason : '';
            const time = (log && (log.Create_Date || log.Operation_Datetime)) ? `（${log.Create_Date || log.Operation_Datetime}）` : '';
            return `${idx + 1}. ${reason}${time}`;
        },
        // 格式化地址（省市区+详细地址）
        formatAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        // 剩余量（兼容无该字段的情况）
        getRemainQuantity(s) {
            if (!s) return '';
            if (s.Remain_Quantity !== undefined && s.Remain_Quantity !== null) return s.Remain_Quantity;
            const t = Number(s.Total_Quantity || 0);
            const sold = Number(s.Sales_Quantity || 0);
            return t - sold;
        },
        openContractDialog(row) {
            this.currentContractRow = row || null;
            this.dialogContractVisible = true;
        },
        startOnlineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            this.$message.success('已选择：线上签约');
        },
        startOfflineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            this.$message.success('已选择：线下签约');
        },
        // 打开阶段付款弹窗
        openPayDialog(orderRow, stageRow) {
            this.payContext = { order: orderRow, stage: stageRow };
            this.payForm = { amount: '', voucherList: [] };
            this.dialogPayVisible = true;
        },
        onVoucherChange(file, fileList) {
            const f = file.raw || file;
            if (!f || !String(f.type || '').startsWith('image/')) {
                this.$message.error('仅支持上传图片文件');
                this.payForm.voucherList = [];
                return;
            }
            const maxSize = 10 * 1024 * 1024; // 10MB
            if (f.size && f.size > maxSize) {
                this.$message.error('图片大小不得超过10MB');
                this.payForm.voucherList = [];
                return;
            }
            this.payForm.voucherList = fileList.slice(0, 1);
        },
        onVoucherRemove(file, fileList) {
            this.payForm.voucherList = fileList;
        },
        // 打开收款详情弹窗（展示付款时填的内容）
        async openReceiptDialog(orderRow, stageRow) {
            this.receiptContext = { order: orderRow, stage: stageRow };
            const orderAmount = orderRow && orderRow.Amount ? String(orderRow.Amount) : '';
            const stageDueAmount = (stageRow && stageRow.dueAmount !== undefined && stageRow.dueAmount !== null && stageRow.dueAmount !== '')
                ? String(stageRow.dueAmount) : '';
            let actualAmount = '';
            let voucherUrl = '';
            let stageDueAmountFallback = '';
            try {
                const arr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order_paystages',
                    Condition: `Acquisition_Order_SerialNumber='${orderRow.Acquisition_Order_SerialNumber}' AND Stage_Name='${String(stageRow.stage || '').replace(/'/g, "''")}'`
                });
                let rec = null;
                if (Array.isArray(arr) && arr.length > 0) {
                    rec = arr[0];
                } else if (arr && Array.isArray(arr.Data) && arr.Data.length > 0) {
                    rec = arr.Data[0];
                }
                if (rec) {
                    // 兼容不同字段名：优先 Paid_Amount，备用 Payment_Amount
                    actualAmount = rec.Paid_Amount || rec.Payment_Amount || '';
                    voucherUrl = rec.Picture_URL || '';
                    stageDueAmountFallback = rec.Trading_Amount || '';
                }
            } catch (e) {}
            // 回退：若表未查到，尝试用阶段行聚合的 paidAmount
            if (!actualAmount && stageRow && stageRow.paidAmount !== undefined && stageRow.paidAmount !== null && stageRow.paidAmount !== '') {
                actualAmount = String(stageRow.paidAmount);
            }
            this.receiptView = {
                contractAmount: orderAmount,
                stageDueAmount: stageDueAmount || stageDueAmountFallback || '',
                actualAmount: actualAmount,
                voucherUrl: voucherUrl
            };
            this.dialogReceiptVisible = true;
        },
        async confirmPay() {
            if (!this.payContext || !this.payContext.order) {
                this.$message.error('上下文缺失，无法付款');
                return;
            }
            const order = this.payContext.order;
            const stage = this.payContext.stage || {};
            const amountNum = Number(this.payForm.amount || 0);
            if (!Number.isFinite(amountNum) || amountNum <= 0) {
                this.$message.error('请输入有效的付款金额');
                return;
            }
            this.paySaving = true;
            try {
                // 上传电子凭证（如果选择了文件）
                let voucherPath = '';
                if (this.payForm.voucherList && this.payForm.voucherList.length > 0) {
                    try {
                        const fileObj = this.payForm.voucherList[0].raw || this.payForm.voucherList[0];
                        const uploadRes = await generalApi.generalUploadStream(fileObj);
                        voucherPath = (uploadRes && (uploadRes.Path || uploadRes.url || uploadRes.File_Path)) || '';
                    } catch (e) {
                        this.$message.warning('凭证上传失败，已忽略');
                    }
                }

                // 1) 查询订单原值以便累计 Paid_Amount（acquisition_order）
                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${order.Acquisition_Order_SerialNumber}'`
                });
                if (!Array.isArray(orderArr) || orderArr.length !== 1) {
                    this.$message.error('未找到订单数据或存在重复记录');
                    this.paySaving = false;
                    return;
                }
                const od = orderArr[0];
                const oldPaid = Number(od.Paid_Amount || 0);
                const newPaid = accAdd(oldPaid, amountNum);
                od.Paid_Amount = String(newPaid);

                // 计算本次应付金额：优先金额×百分比；缺失百分比时回退显示阶段应付金额
                const totalAmount = Number(order.Amount || 0);
                const hasPercent = (stage.percent !== undefined && stage.percent !== null && stage.percent !== '' && !Number.isNaN(Number(stage.percent)));
                const percentVal = hasPercent ? Number(stage.percent) : null;
                const tradingAmountNum = (Number.isFinite(totalAmount) && Number.isFinite(percentVal))
                    ? Number((totalAmount * percentVal / 100).toFixed(2))
                    : Number((stage.dueAmount !== undefined && stage.dueAmount !== null && stage.dueAmount !== '' ? stage.dueAmount : 0));

                // 2) 查询当前阶段付款记录：若存在则累计，否则新增（acquisition_order_paystages）
                let stageModify = null;
                let stageAdd = null;
                try {
                    const stageArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'acquisition_order_paystages',
                        Condition: `Acquisition_Order_SerialNumber='${order.Acquisition_Order_SerialNumber}' AND Stage_Name='${String(stage.stage || '').replace(/'/g, "''")}'`
                    });
                    if (Array.isArray(stageArr) && stageArr.length === 1) {
                        stageModify = stageArr[0];
                        const sOld = Number(stageModify.Paid_Amount || 0);
                        stageModify.Paid_Amount = String(accAdd(sOld, amountNum));
                        // 凭证图片存入 Picture_URL 字段
                        if (voucherPath) stageModify.Picture_URL = voucherPath;
                        // 同步本次应付金额 Trading_Amount
                        if (Number.isFinite(tradingAmountNum)) stageModify.Trading_Amount = String(tradingAmountNum);
                        stageModify.Collection_Date = getYMDHMSDate();
                        stageModify.Row_Status = '已付款';
                    } else {
                        stageAdd = {
                            Acquisition_Order_Paystages_SerialNumber: '',
                            Acquisition_Order_SerialNumber: order.Acquisition_Order_SerialNumber,
                            Stage_Name: stage.stage || '',
                            Percent: stage.percent !== undefined ? stage.percent : '',
                            Due_Amount: stage.dueAmount !== undefined ? stage.dueAmount : '',
                            Trading_Amount: Number.isFinite(tradingAmountNum) ? String(tradingAmountNum) : '',
                            Paid_Amount: String(amountNum),
                            Collection_Date: getYMDHMSDate(),
                            Row_Status: '已付款',
                        };
                        // 凭证图片存入 Picture_URL 字段
                        if (voucherPath) stageAdd.Picture_URL = voucherPath;
                    }
                } catch (e) {
                    // 表不存在或查询失败时，仍然只更新订单累计金额
                }

                const dataset = { Modify: { acquisition_order: [od] }, Add: { base_operation_log: [] } };
                if (stageModify) {
                    dataset.Modify['acquisition_order_paystages'] = [stageModify];
                }
                if (stageAdd) {
                    dataset.Add['acquisition_order_paystages'] = [stageAdd];
                }
                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '求购合同阶段付款',
                    Operation_Main: JSON.stringify({
                        Acquisition_Order_SerialNumber: order.Acquisition_Order_SerialNumber,
                        Stage_Name: stage.stage || '',
                        Pay_Amount: amountNum
                    }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('付款成功');
                    this.dialogPayVisible = false;
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('付款失败，请稍后再试');
            } finally {
                this.paySaving = false;
            }
        },
        // 写入阶段开始时间并计算结束时间（采购合同）
        async upsertStageStart(orderSerial, stageName) {
            try {
                const os = String(orderSerial || '').trim();
                const sn = String(stageName || '').trim();
                if (!os || !sn) return;

                // 查询订单以获取报价编号
                let acqId = '';
                try {
                    const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'acquisition_order',
                        Condition: `Acquisition_Order_SerialNumber='${os.replace(/'/g, "''")}'`
                    });
                    const od = (Array.isArray(orderArr) && orderArr[0]) || null;
                    acqId = od ? (od.Acquisition_Unit_Price_SerialNumber || '') : '';
                } catch (e) {}

                // 获取阶段计划的 Pay_Time（天数）
                let payDays = 0;
                if (acqId) {
                    try {
                        const planRes = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'acquisition_unitprice_staged_payment',
                            Condition: `Acquisition_Unit_Price_SerialNumber='${acqId.replace(/'/g, "''")}' AND Stage_Name='${sn.replace(/'/g, "''")}'`
                        });
                        const planArr = Array.isArray(planRes) ? planRes : (planRes.Data || []);
                        const plan = planArr && planArr[0];
                        payDays = Number((plan && plan.Pay_Time) || 0) || 0;
                    } catch (e) {}
                }

                // 查询现有阶段记录
                let stageRec = null;
                try {
                    const sRes = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'acquisition_order_paystages',
                        Condition: `Acquisition_Order_SerialNumber='${os.replace(/'/g, "''")}' AND Stage_Name='${sn.replace(/'/g, "''")}'`
                    });
                    const sArr = Array.isArray(sRes) ? sRes : (sRes.Data || []);
                    stageRec = (sArr && sArr[0]) || null;
                } catch (e) {}

                const now = new Date();
                const beginStr = getYMDHMSDate(now);
                let endStr = '';
                if (payDays && payDays > 0) {
                    const calc = new Date(now.getTime() + payDays * 24 * 3600 * 1000);
                    endStr = getYMDHMSDate(calc);
                }

                const dataset = { Add: { base_operation_log: [] }, Modify: {} };

                if (stageRec) {
                    const needUpdate = !stageRec.Start_Datetime || !String(stageRec.Start_Datetime).trim();
                    const needEnd = (!stageRec.End_Datetime || !String(stageRec.End_Datetime).trim()) && !!endStr;
                    if (needUpdate || needEnd) {
                        if (needUpdate) stageRec.Start_Datetime = beginStr;
                        if (needEnd) stageRec.End_Datetime = endStr;
                        dataset.Modify['acquisition_order_paystages'] = [stageRec];
                    } else {
                        return; // 已有开始/结束则不重复写入
                    }
                } else {
                    const add = {
                        Acquisition_Order_Paystages_SerialNumber: '',
                        Acquisition_Order_SerialNumber: os,
                        Stage_Name: sn,
                        Start_Datetime: beginStr,
                        End_Datetime: endStr || '',
                        Row_Status: '0'
                    };
                    dataset.Add['acquisition_order_paystages'] = [add];
                }

                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '求购合同阶段开始',
                    Operation_Main: JSON.stringify({ Acquisition_Order_SerialNumber: os, Stage_Name: sn }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });

                try { await generalApi.generalSaveByRequestBody({ Data: dataset }); } catch (e) {}
            } catch (e) { /* 忽略异常 */ }
        },
       
    }
});
});
